<template>
  <div class="data-table">
    <el-table
      v-loading="isLoading"
      :data="displayData"
      style="width: 100%"
      border
      :span-method="mergeSchools ? arraySpanMethod : null">
      <el-table-column label="序号" width="60" align="center">
        <template #default="scope">
          {{ getRowIndex(scope.$index) }}
        </template>
      </el-table-column>
      <el-table-column prop="school" label="学校" min-width="150" />
      <el-table-column prop="competition" label="赛项" width="120" />
      <el-table-column prop="track" label="赛道" width="120" />
      <el-table-column prop="award" label="奖项" width="100" />
      <el-table-column prop="group" label="组别" width="120" />
      <el-table-column prop="province" label="省份" width="100" />
      <el-table-column prop="city" label="市区" width="100" />
      <el-table-column prop="year" label="年份" width="80" align="center" />
      <el-table-column prop="session" label="届数" width="80" align="center" />
      <el-table-column prop="department" label="学院" min-width="150" />
      <el-table-column prop="teacher" label="指导教师" width="120" />
      <el-table-column prop="phone" label="联系电话" width="120" />
      <el-table-column prop="organization" label="组织名称" min-width="150" />
      <el-table-column prop="remarks" label="备注" min-width="120" />
    </el-table>
  </div>
</template>

<script>
import { ref, computed, onMounted, watch, defineExpose } from 'vue'
import axios from 'axios'

export default {
  name: 'DataTable',
  props: {
    filters: {
      type: Object,
      default: () => ({})
    },
    mergeSchools: {
      type: Boolean,
      default: false
    }
  },
  setup(props) {
    const tableData = ref([])
    const isLoading = ref(false)

    const displayData = computed(() => {
      if (!props.mergeSchools) return tableData.value
      
      // Sort data by school to ensure related rows are together
      return [...tableData.value].sort((a, b) => a.school.localeCompare(b.school))
    })

    const arraySpanMethod = ({ row, column, rowIndex, columnIndex }) => {
      if (!props.mergeSchools) return
      
      if (columnIndex === 1) { // 学校列
        const prevRow = displayData.value[rowIndex - 1]
        
        if (!prevRow || prevRow.school !== row.school) {
          let rowspan = 1
          let i = rowIndex + 1
          while (i < displayData.value.length && displayData.value[i].school === row.school) {
            rowspan++
            i++
          }
          return { rowspan, colspan: 1 }
        } else {
          return { rowspan: 0, colspan: 0 }
        }
      } else if (columnIndex === 0) { // 序号列
        const prevRow = displayData.value[rowIndex - 1]
        
        if (!prevRow || prevRow.school !== row.school) {
          // 计算合并的行数
          let rowspan = 1
          let i = rowIndex + 1
          while (i < displayData.value.length && displayData.value[i].school === row.school) {
            rowspan++
            i++
          }
          
          // 计算当前是第几个不同的学校（序号）
          let schoolCount = 1
          for (let i = 0; i < rowIndex; i++) {
            if (i === 0 || displayData.value[i].school !== displayData.value[i-1].school) {
              schoolCount++
            }
          }
          
          return {
            rowspan,
            colspan: 1,
            value: schoolCount // 显示学校序号
          }
        } else {
          return { rowspan: 0, colspan: 0 }
        }
      }
    }

    const fetchData = async (filters) => {
      isLoading.value = true
      try {
        const response = await axios.post('http://localhost:3000/api/data', filters)
        tableData.value = response.data
      } catch (error) {
        console.error('Failed to fetch data:', error)
        tableData.value = []
      } finally {
        isLoading.value = false
      }
    }

    // 监听 filters 变化
    watch(
      () => props.filters,
      (newFilters) => {
        fetchData(newFilters)  // 移除条件判断，始终执行筛选
      },
      { deep: true, immediate: true }
    )

    // 初始加载数据
    onMounted(() => {
      fetchData({})
    })

    // 暴露数据供父组件访问
    defineExpose({
      tableData
    })

    // 添加序号计算方法
    const getRowIndex = (index) => {
      if (!props.mergeSchools) {
        return index + 1
      }
      
      // 计算到当前行为止有多少个不同的学校
      const currentSchool = displayData.value[index].school
      const prevRow = displayData.value[index - 1]
      
      if (!prevRow || prevRow.school !== currentSchool) {
        let count = 1
        for (let i = 0; i < index; i++) {
          if (i === 0 || displayData.value[i].school !== displayData.value[i - 1].school) {
            count++
          }
        }
        return count // 直接返回计数，不需要减1
      }
      return ''  // 对于同一学校的后续行，不显示序号
    }

    return {
      tableData,
      displayData,
      isLoading,
      arraySpanMethod,
      getRowIndex  // 暴露序号计算方法
    }
  }
}
</script>

<style>
.data-table {
  background-color: #fff;
  padding: 20px;
  border-radius: 4px;
}

.el-table {
  margin-top: 10px;
}

/* 适配表格内容过长时的展示 */
.el-table .cell {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
</style>
